import axios from 'axios'
export default {
  // 开启命名空间
  namespaced: true,
  state: {
    list: []
  },
  mutations: {
    setList (state, list) {
      state.list = list
    },
    getCount (state, payload) {
      const goods = state.list.find((item) => item.id === payload.id)
      goods.count = payload.count
    }
  },
  actions: {
    async getCarts (context) {
      // 发送请求获取数据
      const res = await axios.get('http://localhost:3000/cart')
      // actions 不能直接操作 state
      // console.log(res)
      // 调用同模块的 mutations 方法, 可以不用加模块名
      // 调用 mutations 的方法, 保存 list
      context.commit('setList', res.data)
    },
    async updateCount (context, payload) {
      await axios.patch('http://localhost:3000/cart/' + payload.id)
      context.commit('getCount', payload)
    }
  },
  getters: {
    total (state) {
      return state.list.reduce((p, c) => p + c.count, 0)
    },
    totalPrice (state) {
      return state.list.reduce((p, c) => p + c.count * c.price, 0)
    }
  }
}
